package com.yuntoyun.codeavatar.app.activity.main;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.baidu.location.BDLocation;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.yuntoyun.codeavatar.app.R;
import com.yuntoyun.codeavatar.app.activity.basic.LoginActivity;
import com.yuntoyun.codeavatar.app.activity.ext.ConstVal;
import com.yuntoyun.codeavatar.app.activity.ext.HomeBannerHolder;
import com.yuntoyun.codeavatar.app.activity.home.SwitchCityActivity;
import com.yuntoyun.codeavatar.app.fwcore.activity.WebPageActivity;
import com.yuntoyun.codeavatar.app.fwcore.core.AppCoreSign;
import com.yuntoyun.codeavatar.app.fwcore.plug.map.baidu.PlugBaiduLocation;
import com.yuntoyun.codeavatar.app.fwcore.plug.share.wechat.PlugWxShare;
import com.yuntoyun.fwcore.adapter.FwFragmentPagerAdapter;
import com.yuntoyun.fwcore.appext.data.AppData;
import com.yuntoyun.fwcore.base.FwBaseFragment;
import com.yuntoyun.fwcore.model.FwResultJsonDataModel;
import com.yuntoyun.fwcore.model.FwResultJsonListDataModel;
import com.yuntoyun.fwcore.plug.image.glide.PlugGlide;
import com.yuntoyun.fwcore.plug.network.retrofit.FwOkHttp;
import com.yuntoyun.fwcore.tool.login.LoginTool;
import com.yuntoyun.fwcore.util.FwAlertDialogUtil;
import com.yuntoyun.fwcore.util.FwComponentUtil;
import com.yuntoyun.fwcore.util.FwIntentUtil;
import com.yuntoyun.fwcore.util.FwLogUtil;
import com.yuntoyun.fwcore.util.FwPopupWindowUtil;
import com.yuntoyun.fwcore.util.FwRxPermissionUtil;
import com.yuntoyun.fwcore.view.widget.RoundImageView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

import static android.app.Activity.RESULT_OK;

public class HomeFragment extends FwBaseFragment {

    private final String fTag = HomeFragment.class.getSimpleName();

    private final int gActionLoad = 901;
    private final int gActionShare = 902;
    private final int gActionLocation = 903;

    private final int gRcodeCity = 801;

    @BindView(R.id.tvw_location_name)
    TextView tvw_location_name;
    @BindView(R.id.vpr_pages)
    ViewPager vpr_pages;
    @BindView(R.id.cbr_banner)
    ConvenientBanner cbr_banner;
    @BindView(R.id.ivw_share)
    ImageView ivw_share;

    @BindView(R.id.ivw_recommend_1)
    RoundImageView ivw_recommend_1;
    @BindView(R.id.ivw_recommend_2)
    RoundImageView ivw_recommend_2;
    @BindView(R.id.ivw_recommend_3)
    RoundImageView ivw_recommend_3;
    @BindView(R.id.ivw_recommend_4)
    RoundImageView ivw_recommend_4;

    //第三方工具
    private PlugWxShare gPlugWxShare;
    private FwRxPermissionUtil gFwRxRermissionUtil;

    private PopupWindow gSharePopupWindow;
    private View gShareView;
    private String gAttachImagePath;
    private ShareType gShareType;

    private List<Fragment> gTabFragments = new ArrayList<>();
    private List<String> gTabNames = new ArrayList<>();

    private PlugBaiduLocation mLocation = null;
    private double longitude, latitude;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.obj instanceof BDLocation) {
                BDLocation bdLocation = (BDLocation) msg.obj;
                if (null != bdLocation) {
                    longitude = bdLocation.getLongitude();
                    latitude = bdLocation.getLatitude();
                    //节省资源
                    mLocation.stop();
                }
                //转换城市
                setLocationCity();
            }
        }
    };

    @Override
    protected boolean isAgainCreateView() {
        return false;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_main_home;
    }

    @Override
    protected void initView(View layoutView) {
        //定位
        mLocation = new PlugBaiduLocation(fwActivity, mHandler);
        mLocation.init();
        //第三方初始化
        gPlugWxShare = new PlugWxShare(fwActivity);
        gFwRxRermissionUtil = new FwRxPermissionUtil(this);

        this.gShareView = fwLayoutInflater.inflate(R.layout.fragment_main_home_share, null);
        //设置单击事件
        FwComponentUtil.builder().setOnChildViewClick(this.gShareView, new int[]{
                R.id.llt_friend, R.id.llt_friends, R.id.tvw_cancel
        }, this);

        gSharePopupWindow = FwPopupWindowUtil.getPopupWindow(getActivity(), this.gShareView);
    }

    @Override
    protected void initData() {
        //定位数据
        this.doLocation();
//        doReloadData();
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initNavigation() {

    }

    @Override
    protected void messageHandler(Message msg) {

    }

    @Override
    protected void messageHandler(FwResultJsonDataModel model) {
        switch (model.getIndex()) {
            case gActionLoad:
                this.setLoadData(model.getFwData());
                break;
            case gActionShare:
                this.setShareData(model.getFwData());
                break;
            case gActionLocation:
                AppData.setCityId(fwGsonUtil.getString(model.getFwData(), "cityCode"));
                AppData.setCityName(fwGsonUtil.getString(model.getFwData(), "cityName"));
                this.doReloadData();
                break;
        }
    }

    @Override
    protected void messageHandler(FwResultJsonListDataModel model) {

    }

    @OnClick({R.id.llt_location, R.id.ivw_share, R.id.llt_search_container,
            R.id.llt_bar_taobao, R.id.llt_bar_tmall, R.id.llt_bar_jingdong, R.id.llt_bar_pinduoduo, R.id.llt_bar_agriculture,
            R.id.ivw_recommend_1, R.id.ivw_recommend_2, R.id.ivw_recommend_3, R.id.ivw_recommend_4})
    @Override
    public void onClick(View v) {

        if (R.id.ivw_share == v.getId()) {
            if (!LoginTool.isLogin(getActivity(), LoginActivity.class)) {
                return;
            }
        }

        //公用传参使用
        Bundle extras = new Bundle();

        switch (v.getId()) {
            case R.id.llt_location:
                FwIntentUtil.builder().startActivityForResult(getActivity(), SwitchCityActivity.class, gRcodeCity);
                break;
            case R.id.llt_search_container:
//                FwIntentUtil.builder().startActivity(getActivity(), SearchThirdGoodsActivity.class);
                break;
            case R.id.ivw_share:
                gFwRxRermissionUtil.usePermission(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            FwPopupWindowUtil.showPopupWindow(getActivity(), gSharePopupWindow, ivw_share);
                        } else {
                            FwAlertDialogUtil.builder().showCustomDialog(fwActivity, "警告"
                                    , "请开启存储权限!");
                        }
                    }
                }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                break;
            case R.id.llt_friend:
                this.doShare(ShareType.WxFriend);
                this.gSharePopupWindow.dismiss();
                break;
            case R.id.llt_friends:
                this.doShare(ShareType.WxFriends);
                this.gSharePopupWindow.dismiss();
                break;
            case R.id.llt_sina:
                this.doShare(ShareType.Sina);
                this.gSharePopupWindow.dismiss();
                break;
            case R.id.tvw_cancel:
                this.gSharePopupWindow.dismiss();
                break;
            case R.id.llt_bar_taobao:
            case R.id.llt_bar_tmall:
            case R.id.llt_bar_jingdong:
            case R.id.llt_bar_pinduoduo:
                String tagval = FwComponentUtil.builder().getViewTag(v);
                extras.putInt("ext_platform", Integer.parseInt(tagval));
//                FwIntentUtil.builder().startActivity(getActivity(), ThirdMainActivity.class, extras);
                break;
            case R.id.llt_bar_agriculture:
                if (null != MainActivity.getInstance()) {
                    MainActivity.getInstance().switchTabs(1);
                }
                break;
            case R.id.ivw_recommend_1:
            case R.id.ivw_recommend_2:
            case R.id.ivw_recommend_3:
            case R.id.ivw_recommend_4:
                String tmpKeywords = ((RoundImageView) v).getTag().toString().trim();
                extras.putString("ext_keyword", tmpKeywords);
                extras.putInt("ext_platform", ConstVal.APP_THIRD_PLATFORM_JD);
                extras.putBoolean("ext_isRecommend", true);
//                FwIntentUtil.builder().startActivity(getActivity(), ThirdMainSearchListActivity.class, extras);
                break;
            default:
                FwLogUtil.warn(fTag, fwActivity.getString(R.string.fw_txt_no_resid));
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case gRcodeCity:
                if (RESULT_OK == resultCode) {
                    this.doReloadData();
                }
                break;
        }
    }

    //=================================================================================

    public void doReloadData() {
        this.setCityInfo();
        this.doLoadData();
    }

    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    private void setLocationCity() {
        if ((Double.compare(longitude, 0d) == 1) && Double.compare(latitude, 0d) == 1) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("fwUserLongitude", longitude + "");
            map.put("fwUserLatitude", latitude + "");
            AppCoreSign.addSign(map);
            Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getLocation(map);
            super.doPostData(this.gActionLocation, observable, false);
        } else {
            HashMap<String, Object> map = new HashMap<>();
            AppCoreSign.addSign(map);
            Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getLocation(map);
            super.doPostData(this.gActionLocation, observable, false);
        }
    }

    private void doLocation() {
        //定位权限
        gFwRxRermissionUtil.usePermission(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    String pCityId = AppData.getCityId();
                    if (TextUtils.isEmpty(pCityId)) {
                        mLocation.start();
                    } else {
                        doReloadData();
                    }
                } else {
//                    FwAlertDialogUtil.builder().showCustomDialog(fwActivity, "警告"
//                            , "请开定位限，获取更佳体验!");
                    //禁用处理
                    doReloadData();
                }
            }
        }, Manifest.permission.ACCESS_FINE_LOCATION);
    }


    private void setCityInfo() {
        String pCityId = AppData.getCityId();
        String pCityName = AppData.getCityName();
        if ((!TextUtils.isEmpty(pCityId)) && (!TextUtils.isEmpty(pCityName))) {
            tvw_location_name.setText(pCityName);
            tvw_location_name.setTag(pCityId);
        }
    }

    private void setShareData(JsonObject joData) {
        if (null == joData) return;

        String tmpTitle = fwGsonUtil.getString(joData, "title");
        String tmpRemark = fwGsonUtil.getString(joData, "remark");
        String tmpThumbnail = fwGsonUtil.getString(joData, "thumbnail");
        //http://www.hbshuoyun.com/images/s2-banner.jpg|||http://www.baidu.com/img/bd_logo1.png|||http://www.hbshuoyun.com/images/s1-banner.png|||http://www.hbshuoyun.com/images/logo.png
//        String tmpThumbnail = "http://www.baidu.com/img/bd_logo1.png";

        String tmpWebUrl = fwGsonUtil.getString(joData, "redirect_url");

//        PlugMob plugMob = new PlugMob();
//        if (ShareType.WxFriend == gShareType) {
//            plugMob.doThirdShare(Wechat.NAME, tmpTitle, tmpRemark, tmpThumbnail, tmpWebUrl);
//        } else if (ShareType.WxFriends == gShareType) {
//            plugMob.doThirdShare(WechatMoments.NAME, tmpTitle, tmpRemark, tmpThumbnail, tmpWebUrl);
//        }
//        try {
//            //url转码
//            tmpThumbnail = URLDecoder.decode(tmpThumbnail, "UTF-8");
//            FwLogUtil.info(fTag, "Url decode is " + tmpThumbnail);
//
//            PlugGlide.init().downloadImage(tmpThumbnail, new PlugGlide.DownloadImageCallback() {
//                @Override
//                public void download(Bitmap bitmap, Bitmap.CompressFormat format) {
//
//                    FwLogUtil.info(String.format("目标图片大小：%d", bitmap.getByteCount()));
//
//                    //检测当前发布类型
//                    if (gShareType == ShareType.Other) {
//                        Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 150, 150, true);
////                                bitmap.recycle();
//                        // 首先保存图片
//                        File appDir = new File(AppPathData.init().getImgPath(), "thumbnail");
//                        if (!appDir.exists()) {
//                            appDir.mkdir();
//                        }
////                                String fileName = System.currentTimeMillis() + ".jpg";
//                        String fileName = "publish_match_share.jpg";
//                        File file = new File(appDir, fileName);
//                        try {
//                            FileOutputStream fos = new FileOutputStream(file);
//                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
//                            fos.flush();
//                            fos.close();
//                            gAttachImagePath = file.getAbsolutePath();
//                        } catch (FileNotFoundException e) {
//                            FwLogUtil.error(e.getMessage());
//                        } catch (IOException e) {
//                            FwLogUtil.error(e.getMessage());
//                        }
//                    } else {
//                        WxSceneType wxSceneType = WxSceneType.Session;
//                        if (ShareType.WxFriend == gShareType) {
//                            wxSceneType = WxSceneType.Session;
//                        } else if (ShareType.WxFriends == gShareType) {
//                            wxSceneType = WxSceneType.TimeLine;
//                        } else if (ShareType.WxFavorite == gShareType) {
//                            wxSceneType = WxSceneType.Favorite;
//                        }
//                        gPlugWxShare.sendWebpage(tmpWebUrl, tmpTitle, tmpRemark, bitmap, format,
//                                wxSceneType);
//                    }
//                }
//            });
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    private void doShare(ShareType type) {
        this.gShareType = type;
        HashMap<String, Object> map = new HashMap<>();
        AppCoreSign.addSign(map);
        Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getHomeShare(map);
        super.doPostData(this.gActionShare, observable, true);
    }

    private void setLoadData(JsonObject joData) {
        if (null == joData) return;
        //设置城市
        this.initCityView(fwGsonUtil.getJsonObject(joData, "location"));
        //设置Banner
        this.initBannerView(fwGsonUtil.getJsonArray(joData, "banner"));
        //设置推荐词
        this.initRecommendView(fwGsonUtil.getJsonArray(joData, "recommendCate"));
        //设置Tab
        JsonObject joTab = fwGsonUtil.getJsonObject(joData, "tabCate");
        //兼容原有结构实现
        JsonArray jarr = new JsonArray();
        jarr.add(joTab);
        this.initTabsView(jarr);
    }

    private void doLoadData() {
        String pCityId = AppData.getCityId();
        HashMap<String, Object> map = new HashMap<>();
        if (!TextUtils.isEmpty(pCityId)) {
            map.put("fwUserCityId", pCityId);
        }
        AppCoreSign.addSign(map);
        Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getHomeIndex(map);
        super.doPostData(this.gActionLoad, observable, true);
    }

    //布局城市
    private void initCityView(JsonObject joData) {
        if (null == joData) return;

        if (null == tvw_location_name.getTag()) {
            tvw_location_name.setText(fwGsonUtil.getString(joData, "cityName"));
            tvw_location_name.setTag(fwGsonUtil.getString(joData, "cityCode"));
        }
    }

    //布局BannerView
    private void initBannerView(JsonArray jarr) {
//        int pPageIndicator[] = new int[]{R.mipmap.icon_indicator_default, R.mipmap.icon_indicator_checked};
        int pPageIndicator[] = new int[]{R.drawable.style_conenien_banner_indiator_default, R.drawable.style_conenien_banner_indiator_checked};

        List<JsonObject> pBannerList = new ArrayList<>();
        for (int i = 0; i < jarr.size(); i++) {
            pBannerList.add(fwGsonUtil.getJsonObject(jarr, i));
        }
        cbr_banner.setPages(new CBViewHolderCreator() {
            @Override
            public Holder createHolder(View itemView) {
                return new HomeBannerHolder(fwActivity, itemView);
            }

            @Override
            public int getLayoutId() {
                return R.layout.fw_plug_banner_img;
            }
        }, pBannerList).setPageIndicator(pPageIndicator).setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                JsonObject joItem = pBannerList.get(position);
                if (null == joItem) return;

                if (joItem.has("is_jump")) {
                    //是否跳转：0 不跳；1 跳转；
                    if (1 == fwGsonUtil.getInt(joItem, "is_jump")) {
                        Bundle extra = new Bundle();
                        extra.putString("ext_title", "详情");
                        extra.putString("ext_url", fwGsonUtil.getString(joItem, "url"));
                        FwIntentUtil.builder().startActivity(fwActivity, WebPageActivity.class, extra);
                    }
                }
            }
        });

        if (pBannerList.size() > 1) {
            cbr_banner.startTurning(5000);
        }
    }

    //布局推荐
    private void initRecommendView(JsonArray jarr) {
        if (null == jarr) return;

        RoundImageView ivws[] = new RoundImageView[]{
                ivw_recommend_1, ivw_recommend_2, ivw_recommend_3, ivw_recommend_4
        };
        int tmpMaxLen = (jarr.size() > ivws.length) ? ivws.length : jarr.size();
        for (int i = 0; i < tmpMaxLen; i++) {
            JsonObject joItem = fwGsonUtil.getJsonObject(jarr, i);
            ivws[i].setTag(fwGsonUtil.getString(joItem, "keyword"));
            PlugGlide.init().loadImg(getActivity(), fwGsonUtil.getString(joItem, "image"), R.mipmap.fw_icon_empty_rectangle_goods_thumbnail, ivws[i]);
        }
    }

    //布局TabsView
    private void initTabsView(JsonArray jarr) {
        //清除数据
//        gTabNames.clear();
//        gTabFragments.clear();
        if (gTabFragments.size() > 0) {
            //如果已设置数据则不进行刷新
            return;
        }

        for (int i = 0; i < jarr.size(); i++) {
            JsonObject joItem = fwGsonUtil.getJsonObject(jarr, i);
            //组装
            gTabNames.add(fwGsonUtil.getString(joItem, "title"));
            HomeTabFragment pFragment = new HomeTabFragment();
            pFragment.setPlatformType(fwGsonUtil.getInt(joItem, "type"));
            pFragment.setCategories(fwGsonUtil.getJsonArray(joItem, "tabTag"));
            gTabFragments.add(pFragment);
        }
        //ViewPager 未嵌套使用 getFragmentManager()，嵌套使用 getChildFragmentManager()。(否则不加载界面)
        FwFragmentPagerAdapter fwPagerAdapter = new FwFragmentPagerAdapter(getChildFragmentManager(), gTabFragments, gTabNames);
        vpr_pages.setAdapter(fwPagerAdapter);
    }

    //分享类型
    private enum ShareType {
        WxFavorite, WxFriend, WxFriends, Sina, Other
    }
}
